/**
 * Created by yanghaijin on 2018/6/25.
 */

const MsgCode = require('./../../../define/MsgCode');
const OperationType = require('./../data/OperationType');
let PokerRoom = require('./../../../room/PokerRoom');
let PokerGenerator = require('./../../../generator/PokerGenerator');

module.exports = class TenThirtyRoom extends PokerRoom {
    constructor (app, options) {
        super(app, options);
        this._class_name = 'TenThirtyRoom';
        this._pokerGenerator = new PokerGenerator(52);
        this._multiple_bet = [1, 2, 3, 5, 10];
    }

    /**
     * 开始游戏
     * @protected
     * */
    _onStartGame () {
        super._onStartGame();
        this._bet();
        // this._dealCards();
    }

    /**
     * 生成牌数据
     * @protected
     * */
    _generateCards () {
        super._generateCards();
        for (let i = 0; i < this._turn_uids.length; i++) {
            this._uid2cards[this._turn_uids[i]] = this._pokerGenerator.dealCards(1);
        }

        // 生成点数
        for (let uid in this._uid2cards) {
            if (this._uid2cards.hasOwnProperty(uid)) {
                this._uid2point[uid] = 0;
                let arr = this._uid2cards[uid];
                for (let i = 0; i < arr.length; i++) {
                    let o = this._pokerGenerator.getCardConfig(arr[i]);
                    this._uid2point[uid] += o.point;
                    console.info(arr, '生成点数【' + uid + '】', o);
                }
            }
        }
    }

    /**
     * 获得庄家uid
     * @return {String | Number}
     * @protected
     * */
    _getBanker () {
        // super._getBanker();
        return this._players[0].uid;
    }

    /**
     * 广播除庄家外的人下注
     * @protected
     * */
    _bet () {
        super._bet();

        let data = {};
        data['is_banker'] = false;
        data['msg'] = '请下注';
        data.multiple_bet = this._multiple_bet;
        let banker_uid = this._getBanker();
        let uids = this._getAllUidExclude(banker_uid);
        this.send(MsgCode.TurnBet, data, uids);

        let banker_data = {};
        banker_data['is_banker'] = true;
        banker_data.multiple_bet = this._multiple_bet;
        banker_data['msg'] = '等待其他玩家下注';
        this.send(MsgCode.TurnBet, banker_data, banker_uid);
    }

    /**
     * 收到下注消息
     * @param {Object} data
     * @protected
     * */
    _onBet (data) {
        super._onBet(data);

        let uid = data['uid'];
        let bet = data['bet'];

        let o = {};
        o.uid = uid;
        o.bet = bet;
        this.send(MsgCode.OnBet, o);

        this._uid2bet[uid] = bet;
        if (Object.keys(this._uid2bet).length >= this._players.length - 1) {
            this._dealCards();
            this._turn();
            console.log('所有人都已下注，开始发牌和要牌咯！');
        }
    }

    /**
     * 操作
     * @param {Object} [deal_obj] 发牌对象
     * @protected
     * */
    _turn (deal_obj) {
        super._turn();
        if (this._turn_uids.length < 1) {
            this._settlement();
            return;
        }
        // if (this._turn_uids.length <= 1) {
        //     console.log('游戏结束，进入结算了');
        //     return;
        // }
        let turn_uid = this._turn_uids[0];

        let op = [];
        op.push(OperationType.BU_YAO);
        let is_bao = this._uid2point[turn_uid] > 10.5;
        console.log('_uid2point:', this._uid2point);
        if (!is_bao) {
            op.push(OperationType.YAO_PAI);
        }

        let turn_data = {
            turn_uid: turn_uid,
            op: op,
            point: this._uid2point[turn_uid],
            total_time: this._total_time,
            residue_time: this._residue_time
        };
        if (typeof deal_obj !== 'undefined') {
            turn_data.deal_arr = [];
            turn_data.deal_arr.push(deal_obj);
            // turn_data.deal_obj = {
            //     uid: deal_obj.uid,
            //     card_array: deal_obj.card_array
            // };
        }
        this.send(MsgCode.OnTurn, turn_data, turn_uid);

        // 2、其他人
        let uids = this._getAllUidExclude(turn_uid);
        let data = {
            turn_uid: turn_uid,
            total_time: this._total_time,
            residue_time: this._residue_time
        };
        if (typeof deal_obj !== 'undefined') {
            let card_arr = deal_obj.card_arr;
            let arr = [];
            for (let i = 0; i < card_arr.length; i++) {
                arr.push(card_arr[i]);
            }
            arr.splice(0, 1, -1);
            data.deal_arr = [];
            data.deal_arr.push({uid: deal_obj.uid, card_arr: arr});
            // data.deal_obj = {
            //     uid: deal_obj.uid,
            //     card_array: arr
            // };
        }
        this.send(MsgCode.OnTurn, data, uids);
    }

    /**
     * 处理操作
     * @param {Object} data
     * @protected
     * */
    _onTurn (data) {
        super._onTurn(data);
        let uid = data['uid'];
        let op = data['op'];
        let is_bao = this._uid2point[uid] > 10.5;
        switch (op) {
            case OperationType.BU_YAO:
                this._turn_uids.shift();
                this._turn();
                break;
            case OperationType.YAO_PAI:
                let ori_cards = this._uid2cards[uid];
                let new_cards = this._pokerGenerator.dealCards(1);
                this._uid2cards[uid] = ori_cards.concat(new_cards);
                // let arr = this._uid2cards[uid];
                // this._uid2point[uid] = 0;
                for (let i = 0; i < new_cards.length; i++) {
                    let o = this._pokerGenerator.getCardConfig(new_cards[i]);
                    this._uid2point[uid] += o.point;
                    console.info(new_cards, '生成点数【' + uid + '】', o);
                }
                this._turn({uid: uid, card_arr: this._uid2cards[uid]});
                console.info('要牌了:', this._uid2cards[uid]);
                break;
            default:
                break;
        }
    }

    /**
     * 结算
     * @protected
     * */
    _settlement () {
        super._settlement();

        /*
         * 结算流程
         * 1、庄家与每一个玩家进行比较
         * 2、点数大着赢，点数小着输
         * */

        // 1、庄家uid
        let banker_uid = this._getBanker();
        let banker_point = this._uid2point[banker_uid];

        // 2、算分
        let banker_score = 0;
        let infos = [];
        for (let uid in this._uid2point) {
            if (this._uid2point.hasOwnProperty(uid)) {
                let info = {};
                info.uid = uid;
                info.card_array = this._uid2cards[uid];
                info.point = this._uid2point[uid];
                info.score = 0;
                if (!this._isBanker(uid)) {
                    if (banker_point > 10.5) {
                        info.score = this._uid2bet[uid];
                    } else {
                        if (info.point > 10.5) {
                            info.score = this._uid2bet[uid] * -1;
                        } else {
                            info.score = this._uid2bet[uid];
                            if (info.point <= banker_point) {
                                info.score *= -1;
                            }
                        }
                    }
                    banker_score -= info.score;
                }
                infos.push(info);
            }
        }

        // 3、构造结算数据体
        let data = {};
        data.room_state = this._room_state;
        data.infos = [];
        for (let i = 0; i < infos.length; i++) {
            let info = infos[i];
            if (this._isBanker(info.uid)) {
                info.score = banker_score;
            }
            data.infos.push(info);

            // 保存每一轮的数据
            if (!this._rounds_data.hasOwnProperty(info.uid)) {
                this._rounds_data[info.uid] = [];
            }
            let round = {
                point: info.point,
                card_array: info.card_array,
                score: info.score
            };
            this._rounds_data[info.uid].push(round);

            if (!this._uid2totalscore.hasOwnProperty(info.uid)) {
                this._uid2totalscore[info.uid] = 0;
            }
            this._uid2totalscore[info.uid] += info.score;
            info.total_score = this._uid2totalscore[info.uid];
        }
        this.send(MsgCode.Settlement, data);

        // 4、是否进入总结算
        if (this._current_round < this._total_round) {
            this._prepare();
        } else {
            this._totalSettlement();
        }
    }

    /**
     * 总结算
     * @protected
     * */
    _totalSettlement () {
        super._totalSettlement();

        let data = {};
        data.room_state = this._room_state;
        data.house_owner_uid = this._house_owner_uid;
        data.rounds_data = this._rounds_data;
        this.send(MsgCode.TotalSettlement, data);
    }
};